package com.guosen.zebra.framework.starter.config.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;

public class JsonParser {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final Logger LOGGER = LoggerFactory.getLogger(JsonParser.class);

    private JsonParser() {
    }

    public static String toJson(Object object) {
        if (object != null) {
            try {
                return objectMapper().writeValueAsString(object);
            } catch (JsonProcessingException e) {
                LOGGER.error("toJson failed! object: {}", object, e);
            }
        }
        return "";
    }

    public static <T> T toObject(String json, Class<T> clazz) {
        if (StringUtils.hasLength(json)) {
            try {
                return objectMapper().readValue(json, clazz);
            } catch (IOException e) {
                LOGGER.error("toObject failed! json: {}", json, e);
            }
        }
        return null;
    }

    public static <T> T toObject(String json, TypeReference<T> valueTypeRef){
        if (StringUtils.hasLength(json)) {
            try {
                return objectMapper().readValue(json, valueTypeRef);
            } catch (IOException e) {
                LOGGER.error("toObject failed! json: {}", json, e);
            }
        }
        return null;
    }

    public static String toJSONString(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            LOGGER.error("toJSONString failed! object: {}, error message:{}", object, e.getMessage(), e);
        }
        return null;
    }

    public static <T> T toObject(byte[] json, Class<T> clazz) {
        try {
            return objectMapper().readValue(json, clazz);
        } catch (IOException e) {
            LOGGER.error("toObject failed! json: {}", json, e);
        }
        return null;
    }

    public static <T> T toObject(Object obj, TypeReference<T> valueTypeRef) {
        try {
            return objectMapper().convertValue(obj, valueTypeRef);
        } catch (Exception e) {
            LOGGER.error("toObject failed! error: {}", obj, e);
        }
        return null;
    }

    public static ObjectMapper objectMapper() {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return objectMapper;
    }
}
